package by.yakusekmaxim.bookgid.services.impl;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.metamodel.SingularAttribute;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import by.yakusekmaxim.bookgid.dataaccess.BookDao;
import by.yakusekmaxim.bookgid.dataaccess.SeriesDao;
import by.yakusekmaxim.bookgid.datamodel.Book;
import by.yakusekmaxim.bookgid.datamodel.Book_;
import by.yakusekmaxim.bookgid.datamodel.Series;
import by.yakusekmaxim.bookgid.services.SeriesService;

@Service
public class SeriesServiceImpl implements SeriesService {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(SeriesServiceImpl.class);

	@Inject
	private SeriesDao dao;

	@Inject
	private BookDao daoBook;

	@Override
	public Series get(Long id) {
		Series entity = dao.getById(id);
		return entity;
	}

	@Override
	public void saveOrUpdate(Series series) {
		if (series.getId() == null) {
			LOGGER.debug("Save new: {}", series);
			dao.insert(series);
		} else {
			LOGGER.debug("Update: {}", series);
			dao.update(series);
		}
	}

	@Override
	public void delete(Series series) {
		List<Book> bookList = daoBook.getAllBooks(Book_.series, series);
		if (bookList != null) {
			for (Book book : bookList) {
				book.setSeries(null);
				LOGGER.debug("Update: {}", book);
				daoBook.update(book);
			}
		}
		LOGGER.debug("Remove: {}", series);
		dao.delete(series.getId());

	}

	@Override
	public void deleteAll() {
		LOGGER.debug("Remove all series");
		dao.deleteAll();
	}

	@Override
	public Long getCount() {
		return dao.getCount();
	}

	@Override
	public List<Series> getAllSeries(SingularAttribute<Series, ?> attr,
			boolean ascending, int startRecord, int pageSize) {
		return dao.getAllSeries(attr, ascending, startRecord, pageSize);
	}

	@Override
	public List<Series> getAll() {
		LOGGER.debug("Get all Series");
		return dao.getAll();
	}

}
